<?php

namespace app\api\validate;

use app\common\business\Category;
use app\common\business\WorkType;
use app\common\lib\Num;
use app\common\lib\Str;
use think\Validate;

class ApplyRepair extends Validate
{
    protected $rule = [
        'category_id' => 'require|number|checkCategory',
        'contact_person' => 'require',
        'contact_phone' => 'require|checkPhone',
        'address' => 'require',
        'longitude' => 'require',
        'latitude' => 'require',
        'detail' => 'require',
        'content' => 'require',
    ];

    protected $message = [
        'category_id.require' => '报修分类必须',
        'category_id.number' => '报修分类错误',
        'contact_person' => '联系人必须',
        'contact_phone' => '联系电话必须',
        'address' => '地址必须',
        'longitude.require' => '经度必须',
        'longitude.number' => '经度错误',
        'latitude.require' => '纬度必须',
        'latitude.number' => '纬度错误',
        'detail' => '详细地址必须',
        'content' => '内容必须',
    ];

    protected function checkPhone($value, $rule, $data = [])
    {
        $preg = "/^(1\d{10})$/i";
        if (!preg_match($preg,$value)) {
            return "手机号格式错误";
        }
        return true;
    }

    protected function checkCategory($value, $rule, $data = [])
    {
        $categoryBis = new Category();

        $info = $categoryBis->getNormalById($value);
        if (empty($info)){
            return '未查询到分类数据';
        }

        $parent = $categoryBis->getNormalById($info['pid']);
        if (empty($parent)){
            return '未查询到分类数据';
        }

        $grand = $categoryBis->getNormalById($parent['pid']);
        if (empty($grand)){
            return '未查询到分类数据';
        }

        //由于name对应的数组pid不等于0，曲线救国查到最上层
        return $this->checkCommonCategory($grand['name'],$parent['id']);
    }
    protected function checkCommonCategory($name,$value)
    {
        try {
            (new Category())->checkValidValueByName($name,$value);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return true;
    }

    protected $scene = [
        'save'=> ['category_id','contact_person','contact_phone','address','longitude','latitude','detail','content'],
    ];
}